//产品分类
const { Classify } = require('../models/classifyModel');
const { Products } = require('../models/productsModel');

//新增
async function addClassify(req, res) {
  const { name } = req.body;
  const msg = await Classify.create({ name });
  if (msg) {
    res.send({
      status: 1,
      message: '新增成功',
    });
  } else {
    res.send({
      status: 0,
      message: '新增失败',
    });
  }
}

//获取数据
async function getClassify(req, res) {
  const data = await Classify.find();
  res.send({
    status: 1,
    message: '获取成功',
    data,
  });
}

//获取修改的数据

async function getOneClassify(req, res) {
  try {
    const { _id } = req.body;
    const data = await Classify.findById(_id);
    res.send({
      status: 1,
      data,
      message: '获取成功',
    });
  } catch (error) {
    res.send({
      status: 0,
      message: '获取失败',
    });
  }
}

//修改数据

async function updateClassify(req, res) {
  const { _id, name } = req.body;
  const data = await Classify.updateOne({ _id }, { name });
  if (data.nModified === 1) {
    res.send({
      status: 1,
      message: '修改成功',
    });
  } else {
    res.send({
      status: 0,
      message: '修改失败',
    });
  }
}

//删除数据
async function deleteClassify(req, res) {
  const { _id } = req.body;
  try {
    const queryData = await Products.find({ classifyId: _id });
    if (queryData.length) {
      res.send({
        status: 0,
        message: '删除失败',
      });
    } else {
      const data = await Classify.deleteOne({ _id });
      if (data.deletedCount == 1) {
        res.send({
          status: 1,
          message: '删除成功',
        });
      } else {
        res.send({
          status: 0,
          message: '删除失败',
        });
      }
    }
  } catch (error) {
    console.log('删除失败111', error);
    res.send({
      status: 0,
      message: '删除失败',
    });
  }
}

module.exports = {
  getClassify,
  addClassify,
  getOneClassify,
  updateClassify,
  deleteClassify,
};
